<?php


namespace App\Http\Services;

use App\Exceptions\BusinessException;
use App\Models\Dept;
use App\Models\User;
use App\Models\RoleMenu;
use App\Models\UserRole;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserService extends BaseService
{

    public function all(){
        $result = User::orderBy('sort','asc')->orderBy('id','desc')->get();
        return $result->transform(function($item){
            return [
                'id'=>$item->id,
                'name'=>$item->name,
                'value'=>$item->value
            ];
        });
    }

    public function tree(){
        $departments = User::where('status',1)->orderBy('sort','asc')->get()->toArray();

        $dept = $this->buildTree($departments);

        return $dept;
    }


    public function optionTree(){
        $departments = User::orderBy('sort','asc')->get()->toArray();
        $packDept = [];
        foreach ($departments as  $key => $item){
            $packDept[$key]['label'] = $item['name'];
            $packDept[$key]['value'] = $item['id'];
            $packDept[$key]['parent_id'] = $item['parent_id'];
        }

        $dept = $this->buildTree($packDept,0,'value');

        return $dept;
    }

    private function buildTree(array $elements, $parentId = 0,$pk='id')
    {
        $branch = [];
        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {
                $children = $this->buildTree($elements, $element[$pk],$pk);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }

        return $branch;
    }


    public function list($params=[])
    {
        $model = User::whereNull('deleted_at');
        if(isset($params['name'])){
            $model->where('name','like','%'.$params['name'].'%');
        }
        $list = $model->orderBy('id','desc')->paginate();
        return $list;
    }

    public function store($params=[],$id=0)
    {

        $dept = null;
        if($id>0) {
            $user = User::where('id', $id)->first();
            if (empty($user)) {
                throw new Exception('未查询到数据');
            }
            $repeat = User::where('id', '<>', $id)->where(function($q) use ($params){
                $q->where('username',$params['username']);
            })->first();
        }else{
            $repeat = User::where(function($q) use ($params){
                $q->where('username',$params['username']);
            })->first();
        }

        if ($repeat) {
            throw new Exception('数据重复');
        }

        $add = [];
        $add["nickname"]=$params['nickname'];
        $add["username"]= $params['username'];
        $add["mobile"]= $params['mobile'] ?? null;
        $add["gender"]= $params['gender'] ?? null;
        $add["avatar"]= $params['avatar'] ?? null;
        $add["email"]= $params['email'] ?? null;
        $add["status"]= $params['status'] ?? 1;
        $add["dept_id"]= $params['deptId'];

        DB::beginTransaction();
        if(empty($user)){
            $add['password'] = Hash::make('123456');
            $addResult = User::create($add);
            if($addResult === false){
                DB::rollBack();
            }
            $this->setUserRoleIds($params['roleIds'],$addResult->id);
        }else{
            $updateResult = $user->update($add);
            if($updateResult === false){
                DB::rollBack();
            }
            $this->setUserRoleIds($params['roleIds'],$id);
        }
        DB::commit();

        return true;
    }

    public function show($id)
    {
        $result = User::where('id',$id)->first();
        if(empty($result)){
            return [];
        }
        $result->roleIds = UserRole::where('user_id',$id)->pluck('role_id')->toArray();
        $result->deptId = $result->dept_id;
        $result->deptName = optional($result->dept)->name;
        return $result;
    }

    public function getRoleMenuIds($id){
        $menuIds = RoleMenu::where('role_id',$id)->pluck('menu_id')->toArray();
        return $menuIds;
    }

    public function setUserRoleIds($roleIds,$id){
        $user = User::find($id);
        $user->roles()->sync($roleIds);
        return true;
    }

    public function updatePassword($params,$id){
        $user = User::find($id);
        $result = $user->update(['password'=>Hash::make($params['password'])]);
        return $result;
    }
    /**
     * delete
     */
    public function destroy($id)
    {
        $user = User::where('id',$id)->first();
        if (empty($user)) {
            throw new BusinessException('未查询到数据');
        }
        if($user && $user->username == 'admin'){
            throw new BusinessException('超级管理员不能删除');
        }
        $result = $user->delete();
        $user->roles()->detach();
        return $result;
    }



}
